<?php
namespace app\platform\controller;
use app\BaseController;
use app\common\helper\open\OpenPlatformMiniappHelper;
use app\common\logic\DataLogic;
use app\common\model\AppVersionModel;
use app\common\logic\TokenLogic;
use app\common\model\TemplateModel;
use think\facade\Cache;
use think\facade\Db;
use app\common\helper\open\OpenPlatformBaseHelper;

class  Miniapp extends BaseController{
    
    public function getShopInfo(){
        $version = AppVersionModel::where([
            ['app_id','=', $this->request->shop->app_id],
        ])->order(['v'=>'desc'])->find();
        $is_new = 0;
        if(!empty($version) && $this->request->shop->v < $version['v']){
            $is_new = 1;
        }
        $a = '';
        $b = '';
        $c = '';
        $d = '';
//        $Openplatform = new OpenPlatformMiniappHelper();
//        $token = $Openplatform->setShopId($this->request->shopId)->refresh_token();
//        $url = 'https://api.weixin.qq.com/wxa/get_qrcode?access_token='.$token['authorizer_access_token']."&path=pages%2Findex%2Findex";
//        $a = $this->cs_yw_post_data($url);
        // 业务域名 Start
//        if($this->request->shop->yw_status == 10000){
            if($this->request->shop->status == 1 || $this->request->shop->status == 8){
                // component_access_token
//            if(!Cache::get('component_access_token')){
//                $cache_name = 'component_access_token';
//                $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
//                $component_token_data = [
//                    'component_appid' => 'wx9cfb077a41a9f102',
//                    'component_appsecret' => '49d2791b8d619e288f3a5053fe19e120',
//                    'component_verify_ticket' => cache('ticket'),
//                ];
//                $this->gettoken($url,$component_token_data,$cache_name);
//            }
                // authorizer_access_token
//            if(!Cache::get('authorizer_access_token_'.$this->request->shop->wx_app_id)){
//                $cache_name = 'authorizer_access_token_'.$this->request->shop->wx_app_id;
//                $url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token='.Cache::get('component_access_token');
//                $authorizer_token_data = [
//                    'component_appid' => 'wx9cfb077a41a9f102',
//                    'authorizer_appid' => $this->request->shop->wx_app_id,
//                    'authorizer_refresh_token' => $this->request->shop->wx_refresh_token,
//                ];
//                $this->gettoken($url,$authorizer_token_data,$cache_name);
//            }
//            $url = 'https://api.weixin.qq.com/wxa/setwebviewdomain?access_token='.Cache::get('authorizer_access_token_'.$this->request->shop->wx_app_id);
                $Openplatform = new OpenPlatformMiniappHelper();
                $token = $Openplatform->setShopId($this->request->shopId)->refresh_token();
                $url = 'https://api.weixin.qq.com/wxa/setwebviewdomain?access_token='.$token['authorizer_access_token'];
//                $url_data = [
//                    'action' => 'add',
//                    'webviewdomain' => ["http://i.uumo.top"]
//                ];
//                $a = $this->yw_post_data($url,$url_data);
                $ys_url = "https://api.weixin.qq.com/cgi-bin/component/setprivacysetting?access_token=".$token['authorizer_access_token'];
                $ys_data = [
                    'owner_setting' => [
                        "contact_phone" => "18882146753",
                        "notice_method" => "公告",
                    ],
                    'setting_list' => [
                        [
                            "privacy_key" => "UserInfo",
                            "privacy_text" => "用户信息页面展示用户信息"
                        ],
                        [
                            "privacy_key" => "Location",
                            "privacy_text" => "按距离判断最近商家"
                        ],
                        [
                            "privacy_key" => "PhoneNumber",
                            "privacy_text" => "判断用户唯一性"
                        ],
                        [
                            "privacy_key" => "Address",
                            "privacy_text" => "用户收货地址"
                        ],
                        [
                            "privacy_key" => "Album",
                            "privacy_text" => "生成海报"
                        ],
                        [
                            "privacy_key" => "AlbumWriteOnly",
                            "privacy_text" => "生成海报存入用户本地"
                        ],
                        [
                            "privacy_key" => "ChooseLocation",
                            "privacy_text" => "需要更新用户位置信息"
                        ],
                    ]
                ];
                $b = $this->yw_post_data($ys_url,$ys_data);
//                $ys_url = "https://api.weixin.qq.com/cgi-bin/component/getprivacysetting?access_token=".$token['authorizer_access_token'];
//                $ys_data = [
//                    'privacy_ver' => 2,
//                ];
//                $d = $this->yw_post_data($ys_url,$ys_data);
//                var_dump(json_decode($d,true));exit();
                $hf_url = 'https://api.weixin.qq.com/wxa/modify_domain?access_token='.$token['authorizer_access_token'];
                $hf_url_data = [
                    'action' => 'set',
                    'requestdomain' => ["https://i.uumo.top","https://alimg.uumo.top","https://apis.map.qq.com"],
                    'wsrequestdomain' => [],
                    'uploaddomain' => ["https://i.uumo.top"],
                    'downloaddomain' => ["https://i.uumo.top","https://alimg.uumo.top"],
                ];
                $c = $this->yw_post_data($hf_url,$hf_url_data);
                Db::name('shop')->where('shop_id',$this->request->shop->shop_id)->update(['yw_status'=>2]);
                if(empty($this->request->shop->member_register_notice) && !empty($this->request->shop->mp_appid)){
                    $Openplatform = new OpenPlatformMiniappHelper();
                    $mp_token = $Openplatform->setShopId($this->request->shopId)->mp_refresh_token();
                    $template_id = Db::name('weixin_template')->field('template_id,ide')->select();
                    foreach($template_id as $k=>$v){
                        $template_id_url = 'https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token='.$mp_token['authorizer_access_token'];
                        $template_id_url_data = [
                            'template_id_short' => $v['template_id']
                        ];
                        $template_wx_id = json_decode($this->yw_post_data($template_id_url,$template_id_url_data),true);
                        if($template_wx_id['errcode'] == 0){
                            $data = [
                                $v['ide'] => $template_wx_id['template_id']
                            ];
                            Db::name('shop')->where('shop_id',$this->request->shop->shop_id)->update($data);
                        } else {
                            $error = json_encode($template_wx_id);
                            Db::name('test')->insert(['test'=>$error]);
                        }
                    }
                }
            }
//        }
        // 业务域名 End
        return $this->success([
            'auth' => [
                'shop_id'               => $this->request->shop->shop_id,
                'app_id'                => $this->request->shop->app_id,
                'name'                  => $this->request->shop->name,
                'wx_app_id'             => $this->request->shop->wx_app_id,
                'wx_face'               => $this->request->shop->wx_face,
                'wx_name'               => $this->request->shop->wx_name,
                'wx_principal_name'     => $this->request->shop->wx_principal_name,
                'status'                => $this->request->shop->status,
                'is_upgrade'            => $this->request->shop->is_upgrade,
                'code_status'           => $this->request->shop->code_status,
                'error_msg'             => $this->request->shop->error_msg,
                'v'                     => $this->request->shop->v,
                'is_new'                => $is_new,
                'aaa'                   => $a,
                'bbb'                   => $b,
                'ccc'                   => $c,
                'ddd'                   => $d,
                'mp_status'             => $this->request->shop->mp_status,
            ],
        ]);
    }

    // 获取token
    public function gettoken($url,$data,$cache_name){
        $component_token = $this->post_data($url,json_encode($data));
        $component_token = json_decode($component_token,true);
        if(array_key_exists("errcode",$component_token)){
            Cache::delete('component_access_token');
        }
        if($cache_name == 'component_access_token'){
            Db::name('test_token')->insert(['token'=>$component_token['component_access_token'],'create_time'=>time(),'type'=>$cache_name]);
            Cache::set($cache_name, $component_token['component_access_token'], 7000);
        } else {
            Db::name('test_token')->insert(['token'=>$component_token['authorizer_access_token'],'create_time'=>time(),'type'=>$cache_name]);
            Cache::set($cache_name, $component_token['authorizer_access_token'], 7000);
        }

    }

    // post请求
    public function post_data($url,$data){
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS =>$data,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
    public function yw_post_data($url,$data){
        $json_data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS =>$json_data,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }

    public function cs_yw_post_data($url){
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }

    public function getAuth(){
        $callbackUrl = $this->request->param('callback','','security_editor_html');
        $OpenPlatformMiniappHelper = new OpenPlatformMiniappHelper();
        $url = $OpenPlatformMiniappHelper->setShopId($this->request->shop)->getAuthUrl($callbackUrl,2);
        return $this->success([
            'url' => $url
        ]);
    }
    
    public function callBack(){
        $auth_code = $this->request->param('auth_code');
        $OpenPlatformMiniappHelper = new OpenPlatformMiniappHelper();
        $res = $OpenPlatformMiniappHelper->setShopId($this->request->shop)->authCallback($auth_code);
        if(true === $res){
            return $this->success('授权成功');
        }
        return $this->error($res);
    }

    // 获取公众号授权
    public function getMpappAuth(){
        $callbackUrl = $this->request->param('callback','','security_editor_html');
        $OpenPlatformMiniappHelper = new OpenPlatformMiniappHelper();
        $url = $OpenPlatformMiniappHelper->setShopId($this->request->shop)->getAuthUrl($callbackUrl,1);
        return $this->success([
            'url' => $url
        ]);
    }
    // 公众号回调
    public function mpcallBack(){
        $auth_code = $this->request->param('auth_code');
        $OpenPlatformMiniappHelper = new OpenPlatformMiniappHelper();
        $res = $OpenPlatformMiniappHelper->setShopId($this->request->shop)->mpauthCallback($auth_code);
        if(true === $res){
            return $this->success('授权成功');
        }
        return $this->error($res);
    }
    
    
    public function getCategories(){
        $OpenPlatformMiniappHelper = new OpenPlatformMiniappHelper();
        $res = $OpenPlatformMiniappHelper->setShopId($this->request->shop)->getCategories();
        if($res == false){
            return $this->error('暂未配置小程序分类');
        }
        return $this->success([
            'cats' => $res
        ]);
    }
    
    public function uploadCode(){
        Db::name('shop')->where('shop_id',$this->request->shop->shop_id)->update(['yw_status'=>1]);
        $OpenPlatformMiniappHelper = new OpenPlatformMiniappHelper();
        $res =  $OpenPlatformMiniappHelper->setShopId($this->request->shop)->upload();
        if($res !== true){
            return $this->error($res);
        }
        return $this->success('上传成功');
    }
    
    public function submit(){
        $datas = [
            'title'         => $this->request->param('title'),
            'tag'           => $this->request->param('tag'),
            'first_id'      => $this->request->param('first_id'),
            'second_id'     => $this->request->param('second_id'),
            'first_class'   => $this->request->param('first_class'),
            'second_class'  => $this->request->param('second_class'),
        ];
        if(empty($datas['title'])){
            return $this->error('请填写标题');
        }
        if(empty($datas['tag'])){
            return $this->error('请填写标签');
        }
        if(empty($datas['first_id']) || empty($datas['second_id']) || empty($datas['first_class']) || empty($datas['second_class'])){
            return $this->error('请选择分类');
        }
        $OpenPlatformMiniappHelper = new OpenPlatformMiniappHelper();
        $res =  $OpenPlatformMiniappHelper->setShopId($this->request->shop)->submit($datas);
        if($res !== true){
            return $this->error($res);
        }
        return $this->success('提交审核成功');
    }
    
    //撤回审核
    public function  back(){
        $OpenPlatformMiniappHelper = new OpenPlatformMiniappHelper();
        $res =  $OpenPlatformMiniappHelper->setShopId($this->request->shop)->back();
        if($res !== true){
            return $this->error($res);
        }
        return $this->success('撤回成功');
    }
    
    public function online(){
        $OpenPlatformMiniappHelper = new OpenPlatformMiniappHelper();
        $res =  $OpenPlatformMiniappHelper->setShopId($this->request->shop)->online();
        if($res !== true){
            return $this->error($res);
        }
        return $this->success('撤回成功');
    }
    
    public function getTestQrcode(){
        $path   = $this->request->param('path');
        if(empty($path)){
            $path = '/pages/client/index';
        }
        $t = $this->request->time();
        $sign = md5($this->request->shopId.'|'.$path.'|'.$t.'|'. TokenLogic::getAppQrSignToken());
        $url = $this->request->domain().'/platform/miniapp/testQrcodeImg?shop_id='.$this->request->shopId.'&t='.$t.'&path='.urlencode($path).'&sign='.$sign;
        return $this->success([
            'img' => $url
        ]);
    }
    
    public function testQrcodeImg(){
        $shop_id = $this->request->param('shop_id/d');
        $path   = $this->request->param('path');
        $sign   = $this->request->param('sign');
        $t      = $this->request->param('t/d');
        $mysign = md5($shop_id.'|'.$path.'|'.$t.'|'.TokenLogic::getAppQrSignToken());
        if(empty($sign)) die('NO DATA');
        if($sign != $mysign) die('NO DATA');
        $OpenPlatformMiniappHelper = new OpenPlatformMiniappHelper();
        echo $OpenPlatformMiniappHelper->setShopId($shop_id)->getTestQrcode($path);
    }
    
    public function qrcodeImg(){
        $shop_id = $this->request->param('shop_id/d');
        $path   = $this->request->param('path');
        $sign   = $this->request->param('sign');
        $t      = $this->request->param('t/d');
        $mysign = md5($shop_id.'|'.$path.'|'.$t.'|'.TokenLogic::getAppQrSignToken());
        if(empty($sign)) die('NO DATA');
        if($sign != $mysign) die('NO DATA');
        $OpenPlatformMiniappHelper = new OpenPlatformMiniappHelper();
        echo $OpenPlatformMiniappHelper->setShopId($shop_id)->getQrcode($path);
    }
    
    public function getQrcode(){
        $path = $this->request->param('path');
        $t = $this->request->time();
        $sign = md5($this->request->shopId.'|'.$path.'|'.$t.'|'. TokenLogic::getAppQrSignToken());
        $url = $this->request->domain().'/platform/miniapp/qrcodeImg?shop_id='.$this->request->shopId.'&t='.$t.'&path='.urlencode($path).'&sign='.$sign;
        return $this->success([
            'img' => $url
        ]);
    }


    public function getAppTemplateList()
    {
        $where=[
            ['app_id','=',$this->request->appId],
            ['is_online','=',1]
        ];
        $template_model= new TemplateModel();
        $field="*";
        $append=['add_time_format'];
        $order=['add_time'=>'desc'];
        $return = DataLogic::getDataList($template_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        return $this->success($return);
    }
    
    
} 